import json

from django.contrib.auth.models import User
from django.db.models import Q
from django.forms import model_to_dict
from rest_framework import viewsets, mixins, status
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import GenericViewSet
from rest_framework_simplejwt.tokens import RefreshToken
from rest_framework_simplejwt.views import TokenObtainPairView

from chat_api.serializer import *


def get_tokens_for_user(user):
    refresh = RefreshToken.for_user(user)

    return {
        'refresh_token': str(refresh),
        'token': str(refresh.access_token),
    }


class MyTokenObtainPairView(TokenObtainPairView):
    serializer_class = MyTokenObtainPairSerializer


class UserInfoView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request, *args, **kwargs):
        data = model_to_dict(request.user)
        data['token'] = get_tokens_for_user(request.user)['token']
        del data['password']
        return Response(data)


class RegisterView(APIView):

    def post(self, request, *args, **kwargs):
        username = request.data.get("username")
        password = request.data.get("password")
        u = User.objects.create_user(username=username, password=password, first_name="昵称"+username)
        return Response(model_to_dict(u))


class FriendView(viewsets.ModelViewSet):
    permission_classes = [IsAuthenticated]
    serializer_class = FriendSerializer
    queryset = Friend.objects.all()

    def list(self, request, *args, **kwargs):
        user = request.user
        list = Friend.objects.filter(Q(user1_id=user.id) & Q(status=1) | Q(user2_id=user.id) & Q(status=1))
        data = []
        for i in list:
            if i.user1.id == user.id:
                data.append(model_to_dict(i.user2, exclude=['password']))
            else:
                data.append(model_to_dict(i.user1, exclude=['password']))
        return Response(data)

    def create(self, request, *args, **kwargs):

        if not request.data.get("id"):
            return Response({"msg": "请填写完整参数"})
        id = int(request.data.get("id"))
        if int(request.user.id) == id:
            return Response({"msg": "不能添加自己为好友"})

        try:
            a = User.objects.get(id=id)
        except:
            return Response({"msg": "没有该用户"})

        try:
            a = Friend.objects.get(user1_id=request.user.id, user2_id=id)
            if a.status == 0:
                return Response({"msg": "请勿重复申请"})
            else:
                return Response({"msg": "对方已是你的好友"})
        except:
            pass

        try:
            b = Friend.objects.get(user2_id=request.user.id, user1_id=id)
            if b.status == 0:
                return Response({"msg": "请勿重复申请"})
            else:
                return Response({"msg": "对方已是你的好友"})
        except:
            pass

        Friend.objects.create(user1_id=request.user.id, user2_id=request.data.get("id"), status=0)
        return Response({"msg": "申请成功"})

    @action(methods=['GET'], detail=False)
    def hope(self, request, *args, **kwargs):
        user = request.user
        list = Friend.objects.filter(Q(user2_id=user.id) & Q(status=0))
        data = []
        for i in list:
            data.append(model_to_dict(i.user1, exclude=['password']))
        return Response(data)

    @action(methods=['POST'], detail=False)
    def agree(self, request, *args, **kwargs):
        a = Friend.objects.get(Q(user1_id=request.data.get("user1")) & Q(user2_id=request.data.get("user2")))
        a.status = 1
        a.save()
        return Response({})
